package com.wthink.newMain.main

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.IdRes
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import com.lenzshd.services.GPIOProc
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.Constants
import com.wthink.hzgj.R
import com.wthink.hzgj.data.domain.BusDispatch
import com.wthink.hzgj.databinding.ActivityNewMainBinding
import com.wthink.hzgj.main.viewmodel.CheckinViewModel
import com.wthink.hzgj.util.CustomKeyEventProc
import com.wthink.hzgj.util.PreferencesUtils
import com.wthink.hzgj.util.`interface`.JT8b07CallBack
import com.wthink.hzgj.util.`interface`.NoticeCallBack
import com.wthink.newMain.main.viewmodel.MainNewViewModel
import com.wthink.newMain.msg.MsgFragment
import com.wthink.newMain.newBusiness.NewBusinessFragment
import com.wthink.newMain.newCamera.NewCameraFragment
import com.wthink.newMain.schedlePlan.SchedlePlanFragment
import com.wthink.newMain.serviceVoice.ServiceVoiceFragment
import com.wthink.newMain.settings.MenuActivity
import com.wthink.newMain.settings.SettingsActivity
import com.wthink.newMain.view.LoginQuitDialog
import kotlinx.android.synthetic.main.activity_new_main.*
import java.util.*

@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
class MainNewActivity : AppCompatActivity(), TextToSpeech.OnInitListener {

    lateinit var binding: ActivityNewMainBinding
    private val viewModel by viewModels<MainNewViewModel>()
    private val checkinViewModel by viewModels<CheckinViewModel>()
    var textToSpeech: TextToSpeech? = null

    private val quitLoginDialog: LoginQuitDialog by lazy {
        LoginQuitDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        )
        binding = DataBindingUtil.setContentView(this, R.layout.activity_new_main)
        binding.lifecycleOwner = this
        binding.viewModel = viewModel
        binding.checkinViewModel = checkinViewModel

        GPIOProc.AmplifierPw(1)
        GPIOProc.MicPw(1)

        PreferencesUtils.saveValue("isSelf", false)

        textToSpeech = TextToSpeech(BusApplication.busContext, this)

        addFragment(NewHomeFragment())

        binding.back.setOnClickListener {
            showMain()
        }

        binding.ivCamera.setOnClickListener {
            // nav.navTo(NewCameraFragment::class.java, R.id.newCameraFragment)
            replaceFragment(NewCameraFragment())
            iv_camera.isSelected = true
            iv_server.isSelected = false
            iv_business.isSelected = false
            iv_schedle.isSelected = false
            iv_msg.isSelected = false
            iv_settings.isSelected = false

        }

        binding.ivServer.setOnClickListener {
            replaceFragment(ServiceVoiceFragment())
            iv_server.isSelected = true
            iv_business.isSelected = false
            iv_schedle.isSelected = false
            iv_msg.isSelected = false
            iv_camera.isSelected = false
            iv_settings.isSelected = false
        }

        binding.ivBusiness.setOnClickListener {
            replaceFragment(NewBusinessFragment())
            iv_business.isSelected = true
            iv_server.isSelected = false
            iv_schedle.isSelected = false
            iv_msg.isSelected = false
            iv_camera.isSelected = false
            iv_settings.isSelected = false
        }

        binding.ivSchedle.setOnClickListener {
            replaceFragment(SchedlePlanFragment())
            iv_schedle.isSelected = true
            iv_server.isSelected = false
            iv_business.isSelected = false
            iv_msg.isSelected = false
            iv_camera.isSelected = false
            iv_settings.isSelected = false
            schedle_notice.visibility = View.GONE
        }

        binding.ivMsg.setOnClickListener {
            replaceFragment(MsgFragment())
            iv_msg.isSelected = true
            iv_server.isSelected = false
            iv_business.isSelected = false
            iv_schedle.isSelected = false
            iv_camera.isSelected = false
            iv_settings.isSelected = false
            msg_notice.visibility = View.GONE
        }

        binding.ivSettings.setOnClickListener {
           // iv_settings.isSelected = false
            val intent = Intent(this, MenuActivity::class.java)
            startActivity(intent)
        }

/*
        viewModel.setCameraCall(object :
            MainNewViewModel.CameraCallBack {
            override fun cameraCall(content: String) {
                runOnUiThread {
                    if (content == "1") {
                        replaceFragment(NewCameraFragment())
                    } else if (content == "2") {
                        showMain()
                    }
                }
            }
        })
*/

        viewModel.waitBusState2 {
            if (it == "1") {
                replaceFragment(NewCameraFragment())
            } else if (it == "2") {
                showMain()
            }
        }

        binding.ivQuit.setOnClickListener {
            quitLoginDialog.show()
            quitLoginDialog.setOnclickListener(View.OnClickListener { v ->
                when (v?.id) {
                    R.id.sure -> {
                        quitLoginDialog.dismiss()
                    }
                    R.id.back -> {
                        quitLoginDialog.dismiss()
                    }
                }
            })
        }

        viewModel.set8B07callBack(object : JT8b07CallBack {
            override fun jt8b07callBack() {
                runOnUiThread {
                    binding.schedleNotice.visibility = View.VISIBLE
                }
            }
        })

        viewModel.setNociceCallBack(object : NoticeCallBack {
            override fun noticeCall(info: String) {
                runOnUiThread {
                    binding.msgNotice.visibility = View.VISIBLE
                    textToSpeech?.speak(info, TextToSpeech.QUEUE_FLUSH, null)
                }
            }
        })

        viewModel.start()
        viewModel.waitBusDispatch {
            runOnUiThread {
                busDispatch(it)
            }
            val boolean = PreferencesUtils.getBoolean("isSelf")
/*
            if (!boolean) {
                val nav = Navigation.findNavController(this, R.id.main)
                val args = Bundle()
                args.putParcelable("dispatch", it)
                nav.navTo(PlanFragment::class.java, R.id.busPlanFragment, args)
            }
*/
            PreferencesUtils.saveValue("isSelf", false)
        }

        viewModel.waitBusCameraCtl({
            if (!viewModel.isCameraShow()) {
                viewModel.cameraSwitchAndGet()
                val nav = Navigation.findNavController(this, R.id.main)
                nav.navTo(NewCameraFragment::class.java, R.id.newCameraFragment)
            }
        }, {
            if (viewModel.isCameraShow()) {
                viewModel.cameraSwitchAndGet()
                val nav = Navigation.findNavController(this, R.id.main)
                nav.popBackStack()
            }
        })
    }

    private fun addFragment(fragment: Fragment) {
        showMain()
        supportFragmentManager
            .beginTransaction()
            //.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out)
            .add(R.id.main_content, fragment, fragment.javaClass.simpleName)
            //.addToBackStack(fragment.javaClass.simpleName)
            .commit()
    }

    private fun replaceFragment(fragment: Fragment) {
        showOther()
        supportFragmentManager
            .beginTransaction()
            //.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out)
            .replace(R.id.other_content, fragment, fragment.javaClass.simpleName)
            // .addToBackStack(fragment.javaClass.simpleName)
            .commit()
    }

    fun <F : Fragment> NavController.navTo(
        fragmentClass: Class<F>, @IdRes resId: Int,
        args: Bundle? = null
    ) {
        val navHostFragment = supportFragmentManager.fragments.first() as NavHostFragment
        val fragments = navHostFragment.childFragmentManager.fragments


        if (fragments.isEmpty()) {
            navigate(R.id.stateFragment, args)
            return
        }

        if (fragmentClass.isAssignableFrom(fragments.first().javaClass)) {
            return
        }

        val find = fragments.find {
            fragmentClass.isAssignableFrom(it.javaClass)

        }

        if (find != null) {
            if (args != null) {
                throw IllegalStateException("not support backto and args not null")
            }
            //popBackStack(resId, false)
        } else {
            navigate(resId, args)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (event?.scanCode) {
            Constants.KEYCODE_MENU -> {
                //跳转进入菜单界面
                //val nav = Navigation.findNavController(this, R.id.main)
                //nav.navTo(MenuListFragment2::class.java, R.id.menuListFragment2)
                //replaceFragment(MenuListFragment2())
            }

            CustomKeyEventProc.KEY_F6, CustomKeyEventProc.KEY_F8, CustomKeyEventProc.CUSTOM_KEYCODE_PLAY -> {
                /*   val navHostFragment: NavHostFragment =
                       supportFragmentManager.fragments.first() as NavHostFragment*/
                val fragments: List<Fragment?> = supportFragmentManager.fragments
                for (fragment: Fragment? in fragments) {
                    if (fragment is NewHomeFragment) {
                        val newHomeFragment: NewHomeFragment = fragment
                        newHomeFragment.setkeyDown(event.scanCode)
                        break
                    }
                }
            }

            Constants.KEYCODE_ALARM -> {
                viewModel.alarmKey()
            }

            Constants.KEYCODE_AUTO -> {
                viewModel.autoKey()
            }

            CustomKeyEventProc.KEY_F1 -> {
                viewModel.setVoice(0)
            }
            CustomKeyEventProc.KEY_F2 -> {
                viewModel.setVoice(1)
            }
            CustomKeyEventProc.KEY_F3 -> {
                viewModel.setVoice(2)
            }

            CustomKeyEventProc.KEY_F4 -> {
                viewModel.setVoice(3)
            }

            CustomKeyEventProc.KEY_F5 -> {
                viewModel.setVoice(4)
            }

            CustomKeyEventProc.KEY_F7 -> {
                viewModel.setVoice(6)
            }

            CustomKeyEventProc.KEY_F9 -> {
                viewModel.setVoice(8)
            }

            CustomKeyEventProc.KEY_F0 -> {
                viewModel.setVoice(9)
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun onInit(status: Int) {
        val result = textToSpeech!!.setLanguage(Locale.CHINA)
        if (result == TextToSpeech.LANG_MISSING_DATA
            || result == TextToSpeech.LANG_NOT_SUPPORTED
        ) {
            Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show()
        }
    }

    fun busDispatch(parcelable: BusDispatch?) {
        /*val navHostFragment: NavHostFragment =
            supportFragmentManager.fragments.first() as NavHostFragment*/
        val fragments: List<Fragment?> = supportFragmentManager.fragments
        for (fragment: Fragment? in fragments) {
            if (fragment is NewHomeFragment) {
                val newHomeFragment: NewHomeFragment = fragment
                newHomeFragment.busDispatch(parcelable)
                break
            }
        }
    }


    fun showMain() {
        other_content.visibility = View.GONE
        main_content.visibility = View.VISIBLE
        iv_camera.isSelected = false
        iv_server.isSelected = false
        iv_business.isSelected = false
        iv_schedle.isSelected = false
        iv_msg.isSelected = false
    }

    fun showOther() {
        other_content.visibility = View.VISIBLE
        main_content.visibility = View.GONE
    }
}